package com.heima.article.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.nntp.Article;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

@Service
public class ArticleFreemarkerServiceImpl  implements ArticleFreemarkerService {
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ApArticleService apArticleService;
    @Override
    @Async
    public void buildArticleFreemarker(ApArticle article, String content) {

if(!StringUtils.isBlank(content)){
    //生成html静态文件
StringWriter sw=new StringWriter();
Template template=null;
    try {
        template = configuration.getTemplate("article.ftl");//获取模板对象
        Map<String,Object> map=new HashMap<>();
        map.put("content",JSONArray.parseArray(content));
        //合成Html
        template.process(map,sw);
    } catch (Exception e){
        e.printStackTrace();
    }

    //通过输入流将文章输入到Minio
InputStream in=new ByteArrayInputStream(sw.toString().getBytes());
    String path= fileStorageService.uploadHtmlFile("", article.getId() + ".html", in);
    //获取返回的url地址
    //将地址封装到文章对象,更新
    LambdaUpdateWrapper<ApArticle> lam=new LambdaUpdateWrapper<>();
    lam.eq(ApArticle::getId,article.getId()).set(ApArticle::getStaticUrl,path);
    apArticleService.update(lam);

}

    }
}
